package com.orientation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orientation.dto.UserLoginParamDto;
import com.orientation.entity.College;
import com.orientation.entity.Role;
import com.orientation.entity.User;
import com.orientation.commom.exception.CustomException;
import com.orientation.mapper.RoleMapper;
import com.orientation.mapper.UserMapper;
import com.orientation.service.CollegeService;
import com.orientation.service.RoleService;
import com.orientation.service.UserService;
import com.orientation.utils.AesUtil;
import com.orientation.utils.BeanConvertUtils;
import com.orientation.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author xuandian
 * @since 2022-3-9
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private HttpServletRequest request;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserService userService;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleService roleService;
    @Resource
    private CollegeService collegeService;



    public LoginVo login(UserLoginParamDto loginParamDto) {
        LoginVo loginVo = null;
        //进行解密以后去数据库查询
        User one = getOne(Wrappers.<User>lambdaQuery().eq(User::getLoginName, loginParamDto.getUsername()).eq(User::getPassword, AesUtil.encrypt(loginParamDto.getPassword())));
        if (one != null) {
            //讲登录信息放入缓存
            request.getSession().setAttribute("user", one);
            //  System.out.println(request.getSession().getAttribute("user"));
            loginVo = new LoginVo();
            loginVo.setUserName(one.getUserName());
            loginVo.setLoginName(one.getLoginName());
            loginVo.setAvatar(one.getAvatar());
            loginVo.setRole(one.getRoleId());
            loginVo.setSid(one.getSid());
            loginVo.setToken(one.getSid() + one.getLoginName());
        }
        return loginVo;
    }

    @Override
    @Transactional
    public void insertUser(User user) {
        if (user != null && !StringUtils.isEmpty(user.getLoginName())) {
            User user1 = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    //    .eq(User::getDeleted, 0)
                    .eq(User::getLoginName, user.getLoginName())
            );
            if (user1 != null) {
                throw new CustomException("18", "此账号已经存在,请勿重复添加");
            }
            //默认头像地址
            user.setAvatar("http://localhost:9998/files/default-avatar.jpg");
            save(user);
        }
    }

    @Override
    public IPage<User> getUser(Integer pageNum, Integer pageSize, String userName, String loginName) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> query = new LambdaQueryWrapper<>();
        //   query.eq(User::getDeleted, 0);
        if (!StringUtils.isEmpty(userName)) {
            query.like(User::getUserName, userName);
        }
        if (!StringUtils.isEmpty(loginName)) {
            query.like(User::getLoginName, loginName);
        }
        page = userMapper.selectPage(page, query);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            throw new CustomException("11", "当前暂无数据");
        }
        //中文排序

        if (!CollectionUtils.isEmpty(page.getRecords())) {
            List<User> userList = page.getRecords();
            for (User user : userList){
                College co = collegeService.getById(user.getCollegeId());
                user.setCollegeName(co.getCollegeName());
                Role role = roleService.getById(user.getRoleId());
                user.setRoleName(role.getName());
            }
            comparatorForChina(userList);
            //从缓存获取当前登录这用户信息
         /*   User user1 = (User) request.getSession().getAttribute("user");
            System.out.println(user1);
            if ( user1==null || StringUtils.isEmpty(user1.getLoginName()) ) {
                throw new CustomException("18","请重新登录");
            }
         && !user1.getLoginName().equals(user.getLoginName())
       */
            //过滤用户名为空的情况  和 列表排除当前登录用户
            List<User> pileStageList = userList.stream().filter((User user) -> !StringUtils.isEmpty(user.getUserName())).collect(Collectors.toList());
            //他根据登录名去重
            List<User> users = pileStageList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(c -> c.getLoginName()))), ArrayList::new));
            //去重后的记录
            page.setRecords(users);
            //去重后的总记录数量
            page.setTotal(users.size());
        }
        return page;
    }

    @Override
    public LoginVo queryMy(String loginName) {
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getLoginName, loginName));
        LoginVo loginVo = new LoginVo();
        if (user != null) {
            Role role = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getSid, user.getRoleId()).groupBy(Role::getSid));
            BeanConvertUtils.copyProperties(user, loginVo);
            loginVo.setName(role.getName());
        }

        return loginVo;
    }

    @Override
    public void updateMy(String loginName, String old, String newPassword, String news, String fileUrl) {
        if (StringUtils.isEmpty(loginName) || loginName.equals("null")) {
            throw new CustomException("18", "重新登录或者参数错误");
        } else {
            User user = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getLoginName, loginName));
            if (!StringUtils.isEmpty(old) && !user.getPassword().equals(old)) {
                throw new CustomException("18", "原密码输入错误");
            }
            if (!StringUtils.isEmpty(newPassword) && newPassword.length() < 6) {
                throw new CustomException("18", "密码长度最少为六位");
            }
            if (!StringUtils.isEmpty(newPassword) && !StringUtils.isEmpty(news) && !newPassword.equals(news)) {
                throw new CustomException("18", "两次密码输入不一致");
            }
            if (!StringUtils.isEmpty(fileUrl)) {
                user.setAvatar(fileUrl);
            }
            if (!StringUtils.isEmpty(newPassword)) {
                user.setPassword(newPassword);
            }

            updateById(user);
        }


    }

    @Override
    public List<User> queryUser() {
        return userService.list(Wrappers.<User>lambdaQuery().eq(User ::getRoleId,2));
    }

    /**
     * 按中文首字母排序
     *
     * @param result
     * @return result
     */
    private List<User> comparatorForChina(List<User> result) {
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        Collections.sort(result, (o1, o2) -> comparator.compare(o1.getUserName(), o2.getUserName()));
        return result;
    }
}
